package com.mooco.dongba.sys.controller;

import com.mooco.dongba.common.pojo.JsonResult;
import com.mooco.dongba.sys.pojo.SysUser;
import com.mooco.dongba.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/doFindPageObjects")
    public JsonResult doFindPageObjects(String username, Integer pageCurrent) {
        return new JsonResult(sysUserService.findPageObject(username, pageCurrent));
    }

    @PostMapping("/doValidById")
    public JsonResult doValidById(Integer id, Integer valid) {
        sysUserService.valid(id, valid);
        return new JsonResult("update ok");
    }

    @RequestMapping("/doSaveObject")
    public JsonResult doSaveObject(SysUser entity, Integer[] roleIds) {
        sysUserService.saveObject(entity, roleIds);
        return new JsonResult("save ok");
    }

    // http://localhost/user/doFindObjectById?id=22
    @RequestMapping("/doFindObjectById")
    public JsonResult doFindObjectById(Integer id) {
        return new JsonResult(sysUserService.findObjectById(id));
    }

    @RequestMapping("/doUpdateObject")
    public JsonResult doUpdateObject(SysUser entity, Integer[] roleIds) {
        sysUserService.updateObject(entity, roleIds);
        return new JsonResult("update ok");
    }

    @RequestMapping("/doUpdatePassword")
    public  JsonResult doUpdatePassword(String pwd, String newPwd, String cfgPwd) {
        sysUserService.updatePassword(pwd, newPwd, cfgPwd);
        return new JsonResult("update ok");
    }

    @RequestMapping("/doLogin")
    public JsonResult doLogin(String username, String password, Boolean isRememberMe) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        if (isRememberMe) {
            token.setRememberMe(isRememberMe);
        }
        subject.login(token);
        return new JsonResult("login ok");
    }
}
